package com.leadingsoft.pwxk.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.leadingsoft.common.dto.TableResultDto;
import com.leadingsoft.pwxk.converter.YearPlanConverter;
import com.leadingsoft.pwxk.dto.SearchDto;
import com.leadingsoft.pwxk.dto.YearPlanDto;
import com.leadingsoft.pwxk.model.YearPlan;
import com.leadingsoft.pwxk.service.YearPlanService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(description = "年度计划")
@RestController
@RequestMapping("api/yearPlan")
public class YearPlanController {

	@Value("${export.oldFile}")
	private String oldFile;

	@Value("${export.newFile}")
	private String newFile;

	@Autowired
	YearPlanService yearPlanService;

	@Autowired
	YearPlanConverter yearPlanConverter;

	@ApiOperation("上传execl")
	@PostMapping("upload")
	public Map<String, Object> uploadExc(MultipartHttpServletRequest request) throws IOException {
		return yearPlanService.importData(request);
	}

	@ApiOperation("列表")
	@GetMapping(params = { "draw" })
	public TableResultDto<YearPlanDto> list(
			@PageableDefault(page = 0, size = 10, sort = {"year"}, direction = Direction.DESC) Pageable pageable,
			@RequestParam(value = "draw", required = false) Long draw, SearchDto s) {
		Page<YearPlan> list = yearPlanService.list(pageable, s);
		return TableResultDto.success(draw, list, yearPlanConverter);

	}

	@ApiOperation("核发统计")
	@GetMapping("/statistical")
	public List<Map<String, Object>> getStatistical(@RequestParam(required = false) String year) {
		return yearPlanService.getStatistical(year);
	}

	@ApiOperation("下载execl")
	@GetMapping("/execl")
	public void singleFiledownload(HttpServletRequest request, HttpServletResponse response) {
		String fileName = "年度核发计划.xls";
		OutputStream os = null;
		try {
			HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(getWorkBook(fileName, "")));
			os = response.getOutputStream();
			String agent = request.getHeader("USER-AGENT");
			String fileName_;
			if (StringUtils.isNotBlank(agent) && agent.indexOf("Firefox") > -1) {
				fileName_ = new String((fileName).getBytes(), "ISO8859-1");
			} else {
				fileName_ = URLEncoder.encode((fileName), "UTF-8");
			}
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName_);
			response.setContentType("application/msexcel");
			wb.write(os);
			wb.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private File getWorkBook(String fileName, String userName) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			File inFile = new File(oldFile + fileName);
			File outFile = new File(newFile);
			if (!outFile.exists()) {
				outFile.mkdirs();
			}
			outFile = new File(outFile, userName + "-" + fileName);
			if (outFile.exists() && outFile.isFile()) {
				outFile.delete();
			}

			fis = new FileInputStream(inFile);
			fos = new FileOutputStream(outFile);

			IOUtils.copy(fis, fos);

			return outFile;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(fos);
			IOUtils.closeQuietly(fis);
		}
		return null;
	}

}
